<script setup lang="ts">
import {statusOpts} from "@/utils/status";
import {stallFields} from "@/utils/field";
import {
  createStall,
  deleteStall,
  getStallDetail,
  getStallList,
  StallForm,
  StallQuery,
  updateStall,
} from "@/api/shop/stall";
import {getSupplierOptions} from "@/api/supplier";

defineOptions({
  name: "Stall",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const route = useRoute();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const modelFields = stallFields();
const statusOptions = statusOpts();

const supplierOptions = ref<OptionType[]>([]);
const queryParams = reactive<StallQuery>({
  pageNum: 1,
  pageSize: 10,
});

const shopId = ref(route.query.shop_id); //店铺编号
if (shopId.value) {
  queryParams.shop_id = Number(shopId.value);
}

const lists = ref<StallQuery[]>();
const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<StallForm>({
  status: 1,
});

const rules = reactive({
  shop_id: [{required: true, message: "请选择所属店铺", trigger: "blur"}],
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getStallList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.shop_id = undefined;

  handleQuery();
}

/** 打开表单弹窗 */
function openDialog(roleId?: number) {
  dialog.visible = true;

  getSupplierOptions()
    .then((data) => {
      supplierOptions.value = data.data || [];
      modelFields["shop_id"]["options"] = supplierOptions.value;
    })
    .then(() => {
      if (roleId) {
        dialog.title = "修改档口";
        getStallDetail(roleId).then(({data}) => {
          Object.assign(formData, data);
        });
      } else {
        dialog.title = "新增档口";
      }
    });
}

/** 保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        updateStall(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        createStall(formData)
          .then((res) => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetEditForm();
}

/** 重置表单 */
function resetEditForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteStall(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });

}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form class="pull-left" ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="">
          <el-input v-model="queryParams.keywords" placeholder="档口名称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-button
        v-hasPerm="['shop:stall:add']"
        type="success"
        @click="openDialog()"
        class="pull-right"
      >
        <i-ep-plus/>
        新增
      </el-button>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="lists"
        highlight-current-row
      >
        <el-table-column label="档口名称" prop="title" min-width="100"/>
        <el-table-column label="所属店铺" prop="shop_title"/>
        <el-table-column label="新增时间" prop="create_time"/>
        <el-table-column label="状态" align="center" width="160">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ statusOptions[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <!--            :disabled="scope.row.shop_type == 0 ? true: false"-->
            <el-button v-hasPerm="['shop:stall:edit']" type="primary" size="small" link
                       @click="openDialog(scope.row.id)">
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>

            <!--            :disabled="scope.row.shop_type == 0 ? true: false"-->
            <el-button v-hasPerm="['shop:stall:delete']" type="danger" size="small" link
                       @click="handleDelete(scope.row.id)">
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="540px" @close="closeDialog">
      <el-form ref="objFormRef" :model="formData" :rules="rules" label-width="140px">
        <el-form-item :label="field.title" :prop="fk.toString()" v-for="(field, fk) in modelFields" :key="fk">

          <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
            <el-radio :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
          </el-radio-group>

          <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
            <el-option :key="Number(op.id)" :label="op.title" v-for="op in field.options" :value="Number(op.id)"/>
          </el-select>

          <el-input :type="field.type || 'text'" v-model="formData[fk]" :placeholder="'请输入' + field.title" v-else/>

        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
